﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Expect.VisualStudio.Extensions.Commands.Handlers;

namespace Expect.VisualStudio.Extensions.Commands
{
    public static class CommandFactory
    {
        private static List<ICommand> _commands;

        public static IEnumerable<ICommand> GetFixtureCommands(SelectionResolution resolution)
        {
            if (!resolution.IsFixture) 
                return new List<ICommand>();

            if (_commands == null) InitCommands(resolution.ExpectPackage);

            return _commands.Where(c => c.ShowCommand(resolution)).ToList();
        }

        private static void InitCommands(IExpectPackage pkg)
        {
            _commands = new List<ICommand>();

            var cmdTypes =
                typeof(CommandFactory).Assembly.GetTypes().Where(
                    t => t.IsSubclassOf(typeof(EditorCommand)) && !t.IsAbstract);

            foreach (var cmdType in cmdTypes)
            {
                var inst = (ICommand)Activator.CreateInstance(cmdType, pkg);
                _commands.Add(inst);
            }
            _commands = _commands.OrderBy(c => c.DisplayText).ToList();
        }
    }
}
